package com.lagou.sqlSession;
/*
 * PackageName: com.lagou.sqlSession
 * ClassName:
 * Author:   zhang
 * Date:     Created in 2020/9/29
 * Description:
 * History:
 * <author>        <time>             <version>          <desc>
 * 作者姓名         修改时间            版本号              描述
 * zhang           2020/9/29      1.0
 */

import com.lagou.config.BoundSql;
import com.lagou.config.XMLConfigBuilder;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;
import com.lagou.utils.TokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Title:
 * Project: IPersistence_test
 *
 * @author ZhangKe
 * Created on 2020/9/29
 */
public class SimpleExecutor implements Executor{
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {

        //注册驱动
//        Connection connection = configuration.getDataSource().getConnection();//拿不到connection
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/zdy_mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Hongkong", "root", "root");

        //获取sql，将#{XXX}转化成？,同时完成#{}内的值进行解析存储
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoudSql(sql);

        //获取预处理对象PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //设置参数
        //获取到参数全路径
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);
        //参数列表
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            //反射
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            //暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        //执行SQL
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        ArrayList<Object> objects = new ArrayList<>();

        //封装返回结果集
        while (resultSet.next()){
            Object o = resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                //字段值
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);
            }
            objects.add(o);
        }
        return (List<E>) objects;
    }

    @Override
    public <E> E update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {

        //注册驱动
//        Connection connection = configuration.getDataSource().getConnection();//拿不到connection
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/zdy_mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Hongkong", "root", "root");

        //获取sql，将#{XXX}转化成？,同时完成#{}内的值进行解析存储
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoudSql(sql);

        //获取预处理对象PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText(),Statement.RETURN_GENERATED_KEYS);

        //设置参数
        //获取到参数全路径
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);
        //参数列表
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            Object o=null;
            //如果参数是基本类型或者基本类型的包装类，那么直接获取参数，执行之后的逻辑
            if (parameterTypeClass.getName().contains("java.lang."))
                o = params[0];
            else{
                //反射
                Field declaredField = parameterTypeClass.getDeclaredField(content);
                //暴力访问
                declaredField.setAccessible(true);
                o = declaredField.get(params[0]);
            }
            preparedStatement.setObject(i+1,o);
        }
        //执行SQL
        Integer i = preparedStatement.executeUpdate();
        ResultSet resultSet = preparedStatement.getGeneratedKeys();
        Integer id = null;
        while(resultSet.next()){
            id = resultSet.getInt(1);
        }
        //如果修改、删除，则返回影响结果行数，否则返回最新插入的ID值
        if (id!=null)
            return (E) id;
        else
            return (E) i;
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType!=null){
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }
        return null;
    }

    /**
     * 完成sql的处理和参数绑定
     * @param sql
     * @return
     */
    private BoundSql getBoudSql(String sql) {
        //标记处理类：配置标志解析器，来完成sql中占位符的解析工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //此时完成了sql中的占位符解析
        String parseSql = genericTokenParser.parse(sql);
        //#{}里解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql,parameterMappings);
        return boundSql;
    }
}
